package com.woniuxy.microshoppingcartserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.woniuxy.microshoppingcartserver.bean.Favorite;
import com.woniuxy.microshoppingcartserver.service.FavoriteService;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class FavoriteServiceImpl implements FavoriteService {

    private final String FAVORITE_PREFIX = "favorite:user:";
    private final String FAVORITE_COUNT = "favorite:count";

    @Resource
    private ValueOperations valueOperations;
    @Resource
    private HashOperations hashOperations;
    @Resource
    private ZSetOperations zSetOperations;
    /**
     * 收藏商品
     * 判断是否已经收藏 如果没有就添加到收藏夹，如果已经收藏了就取消收藏
     * 一个商品被多少人收藏：用String显示 key（goodsId） value（用incre）自增，取消收藏用自减
     * hash存一个用户收藏的商品 key（userId） hk（goodsId） hv（goodsInfo对象）
     */
    @Override
    public Integer addFavorite(Integer goodsId,String userId) {
        //判断该用户是否收藏此商品
        String favorite_key = FAVORITE_PREFIX + userId;
        if(isCollect(favorite_key,goodsId)){
            deleteFavorite(goodsId,userId);
            return 0;
        }else{
            //如果没有收藏就添加到收藏夹
            Object goodsObject = valueOperations.get(goodsId.toString());
            //商品对象转换成收藏夹对象存储到favorite:user:userId goodIs FavoriteJSON
            Favorite favorite = new Favorite(goodsId,goodsObject.toString(),Integer.parseInt(valueOperations.get(goodsId.toString()).toString()),new Date().getTime());
            hashOperations.put(favorite_key,goodsId.toString(),JSON.toJSONString(favorite));
            valueOperations.increment(FAVORITE_COUNT+goodsId);
            //返回值为0 成功收藏
            return 1;
        }

    }

    /**
     * 判断商品是否被用户收藏
     * @param favorite_key
     * @param goodsId
     * @return
     */
    public Boolean isCollect(String favorite_key,Integer goodsId){
        valueOperations.setIfAbsent(FAVORITE_COUNT+goodsId,0);
        return hashOperations.hasKey(favorite_key,goodsId.toString());
    }

    /**
     * 查看购物车
     */
    @Override
    public List<Favorite> lookFavotite(Integer start, Integer end,String userId) {
        String favorite_key = FAVORITE_PREFIX + userId;
        //根据用户id获得该用户购物车里的所有物品
        Map map = hashOperations.entries(favorite_key);
        map.forEach((k,v)->{
            //v 是Favorite对象的JSON字符串Object对象
            Favorite favorite = JSONObject.toJavaObject(JSON.parseObject(v.toString()),Favorite.class);
            //更新收藏人数
            favorite.setFavoriteNums(Integer.parseInt(valueOperations.get(favorite.getGoodsId().toString()).toString()));
            //时间作为score存储到zset中
            zSetOperations.add(favorite_key+":look",JSON.toJSONString(favorite),favorite.getCollectTime());
        });
        Set<DefaultTypedTuple<String>> typedTupleSet = zSetOperations.reverseRangeByScoreWithScores(favorite_key+":look",Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITY,start,end);
        List<Favorite> collcetions = new ArrayList<>();
        typedTupleSet.forEach(e->{
            collcetions.add(JSON.toJavaObject(JSON.parseObject(e.getValue().toString()),Favorite.class));
        });
        return collcetions;
    }

    /**
     * 取消收藏
     * @param goodsId
     */
    @Override
    public void deleteFavorite(Integer goodsId,String userId) {
        //如果收藏了就取消
        String favorite_key = FAVORITE_PREFIX + userId;
        hashOperations.delete(favorite_key,goodsId.toString());
        //判断收藏人数是否大于1，收藏人数减1
        if(Integer.parseInt(valueOperations.get(FAVORITE_COUNT+goodsId).toString()) > 0){
            valueOperations.decrement(FAVORITE_COUNT+goodsId);
        }
    }


}
